package com.doublefish.doublefishrobot.ui.video.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.doublefish.doublefishrobot.R;

import java.util.Locale;

/**
 * 作者:dugaofeng on 2024/10/29 14:47
 */
public class VideoPlayerControlView extends FrameLayout {

    private ImageButton exitBtn;
    private VideoCacheSeekBar seekbar;
    private TextView currentTv;
    private TextView totalTv;
    private TextView scaleTv;
    ImageButton playBtn;
    ImageButton fullScreenBtn;

    private Handler handler = new Handler(Looper.getMainLooper());

    private OnVideoPlayerControlViewListner onVideoPlayerControlViewListner;
    private long totalTime;

    public VideoPlayerControlView(Context context) {
        this(context, null);
    }

    public VideoPlayerControlView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoPlayerControlView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public VideoPlayerControlView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();

    }

    private void initView() {
        inflate(getContext(), R.layout.view_video_control, this);
        setVisibility(INVISIBLE);

        exitBtn = findViewById(R.id.iv_exit);
        exitBtn.setVisibility(INVISIBLE);
        currentTv = findViewById(R.id.tv_current);
        totalTv = findViewById(R.id.tv_total);
        scaleTv = findViewById(R.id.tv_scale);
        playBtn = findViewById(R.id.btn_paly);
        fullScreenBtn = findViewById(R.id.btn_fullscreen);
        seekbar = findViewById(R.id.seekbar);

        playBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                playBtn.setSelected(!playBtn.isSelected());
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onPlayBtnClick(playBtn.isSelected());
                }
            }
        });
        exitBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                fullScreenBtn.setSelected(false);
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onFullScreenBtnClick(false);
                }
                exitBtn.setVisibility(INVISIBLE);
            }
        });
        fullScreenBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                fullScreenBtn.setSelected(!fullScreenBtn.isSelected());
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onFullScreenBtnClick(fullScreenBtn.isSelected());
                }
                exitBtn.setVisibility(fullScreenBtn.isSelected() ? VISIBLE : INVISIBLE);
            }
        });
        scaleTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onSpeedBtnClick();
                }
            }
        });

        seekbar.setOnCacheSeekBarListener(new OnCacheSeekBarListener() {
            @Override
            public void onCacheSeekBarChanged(int progress) {
                long currentValue = totalTime * progress / 100 ;
                setSeekBarSeekTime(currentValue, totalTime);
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onSeekbarSeeking();
                }
            }

            @Override
            public void onCacheSeekBarStopChanged(int progress) {
                long currentValue = totalTime * progress / 100 ;
                setSeekBarSeekTime(currentValue, totalTime);
                if (onVideoPlayerControlViewListner != null) {
                    onVideoPlayerControlViewListner.onSeekbarChanged(progress);
                }
            }
        });
    }

    public void setOnVideoPlayerControlViewListner(OnVideoPlayerControlViewListner onVideoPlayerControlViewListner) {
        this.onVideoPlayerControlViewListner = onVideoPlayerControlViewListner;
    }

    //特殊情况 按下系统的返回键 退出全屏
    public void exitFullScreen() {
        fullScreenBtn.setSelected(false);
        exitBtn.setVisibility(INVISIBLE);
    }

    public void setSpeed(String speedText) {
        scaleTv.setText(speedText);
    }

    //设置播放的进度
    public void setPlayTime(long current, long total) {
        //滑块拖动中，先显示滑块的进度， 不显示播放进度
        if (seekbar.isSeeking) {
            return;
        }
        setTime(current, total);
    }

    //设置滑块拖动的进度
    public void setSeekBarSeekTime(long current, long total) {
        setTime(current, total);
    }

    private void setTime(long current, long total) {
        totalTime = total;

        Looper mainLoop = Looper.getMainLooper();
        Looper myLooop = Looper.myLooper();
        boolean isMainThread = (mainLoop == myLooop);
        if (isMainThread) {
            int progress = 0;
            if (total > 0 && current >= 0) {
                progress = (int)(current * 100 / total);
            }
            currentTv.setText(generateTime(current));
            totalTv.setText(generateTime(total));
            seekbar.setPlayProgress(progress);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    int progress = 0;
                    if (total > 0 && current >= 0) {
                        progress = (int)(current * 100 / total);
                    }
                    currentTv.setText(generateTime(current));
                    totalTv.setText(generateTime(total));
                    seekbar.setPlayProgress(progress);
                }
            });
        }
    }

    public void setCacheProgress(int cacheProgress) {
        if (cacheProgress < 0 || cacheProgress > 100) {
            return;
        }
        if (cacheProgress == 100 && seekbar.getCacheProgress() == 100) {
            return;
        }
        Looper mainLoop = Looper.getMainLooper();
        Looper myLooop = Looper.myLooper();
        boolean isMainThread = (mainLoop == myLooop);
        if (isMainThread) {
            seekbar.setCacheProgress(cacheProgress);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    seekbar.setCacheProgress(cacheProgress);
                }
            });
        }
    }

    private String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        if (hours > 0) {
            return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes,
                    seconds);
        } else {
            return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        }
    }



    public interface OnVideoPlayerControlViewListner {
        void onPlayBtnClick(boolean play);
        void onFullScreenBtnClick(boolean fullScreen);
        void onSpeedBtnClick();

        void onSeekbarSeeking();
        void onSeekbarChanged(int progress);
    }


    public static class VideoCacheSeekBar extends FrameLayout {
        private View bgLine;  //底部的线， 表示总进度
        private View cacheLine;   //中间的线， 表示缓冲进度
        private View playLine;  //顶部的线， 表示播放长度
        private View roundBtn; //按钮

        private int viewWidth = 0;  //seekbar 的宽度
        private boolean isSeeking = false; // 是否移动中
        private float lastX;

        private int playProgress = 0;  //播放进度 0-100
        private int cacheProgress = 100;  //缓冲进度 0-100

        private OnCacheSeekBarListener onCacheSeekBarListener;

        public VideoCacheSeekBar(Context context) {
            this(context, null);
        }

        public VideoCacheSeekBar(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }

        public VideoCacheSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            this(context, attrs, defStyleAttr, 0);
        }

        public VideoCacheSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            initView();
        }

        public void setOnCacheSeekBarListener(OnCacheSeekBarListener listener) {
            this.onCacheSeekBarListener = listener;
        }

        @Override
        public void onWindowFocusChanged(boolean hasWindowFocus) {
            super.onWindowFocusChanged(hasWindowFocus);
            //获取到最大值， 并设置初始位置
            if (viewWidth == 0) {
                viewWidth = bgLine.getMeasuredWidth() - dip2px(30);  //-30dp
                ViewGroup.LayoutParams cacheLineLayoutParams = cacheLine.getLayoutParams();
                cacheLineLayoutParams.width = viewWidth;
                cacheLine.setLayoutParams(cacheLineLayoutParams);
            }
        }

        private void initView() {
            inflate(getContext(), R.layout.view_video_cache_seek_bar, this);

            bgLine = findViewById(R.id.line_bg);
            cacheLine = findViewById(R.id.line_cache);
            playLine = findViewById(R.id.line_play);
            roundBtn = findViewById(R.id.round_btn);
        }

        public boolean isSeeking() {
            return isSeeking;
        }

        public void setPlayProgress(int playProgress) {
            // 正在拖动中
            if (isSeeking) {
                return;
            }
            if (playProgress < 0 || playProgress > 100) {
                return;
            }
            this.playProgress = playProgress;

            int offset = viewWidth * playProgress / 100;
            ViewGroup.LayoutParams playLineLayoutParams = playLine.getLayoutParams();
            playLineLayoutParams.width = offset;
            playLine.setLayoutParams(playLineLayoutParams);
        }

        public int getCacheProgress() {
            return cacheProgress;
        }

        public void setCacheProgress(int cacheProgress) {
            if (cacheProgress < 0 || cacheProgress > 100) {
                return;
            }
            this.cacheProgress = cacheProgress;

            int offset = viewWidth * cacheProgress / 100;
            ViewGroup.LayoutParams cacheLineLayoutParams = cacheLine.getLayoutParams();
            cacheLineLayoutParams.width = offset;
            cacheLine.setLayoutParams(cacheLineLayoutParams);
        }

        private int dip2px(float dpValue) {
            final float scale = getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
        
        //点击事件 拖动事件
        @Override
        public boolean onTouchEvent(@NonNull MotionEvent event) {
            if (onCacheSeekBarListener == null) {
                return true;
            }

            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                //点击的位置
                float x = event.getX();
                float y = event.getY();
                //按钮的位置 尺寸
                float roundBtnX = roundBtn.getX();
                float roundBtnY = roundBtn.getY();
                int roundBtnWidth = roundBtn.getMeasuredWidth();  //宽高
                //判断点击的位置是否在按钮的范围
                if (x > roundBtnX && x < roundBtnX + roundBtnWidth && y > roundBtnY && y < roundBtnY + roundBtnWidth) {
                    isSeeking = true;
                    lastX = x;
                }
            } else if (action == MotionEvent.ACTION_MOVE && isSeeking) {
                float x = event.getX();
                int offset = (int)(x - lastX);
                if (offset == 0) {
                    return true;
                }

                int maxWidth = (cacheProgress == 100) ? viewWidth : (viewWidth * cacheProgress / 100);
                ViewGroup.LayoutParams params = playLine.getLayoutParams();
                int width = params.width + offset;
                if (width<0) {
                    width = 0;
                } else if (width > maxWidth) {
                    width = maxWidth;
                }
                //计算当前值
                playProgress = width * 100 / viewWidth;

                params.width = width;
                playLine.setLayoutParams(params);

                onCacheSeekBarListener.onCacheSeekBarChanged(playProgress);
                lastX = x;
            } else {
                onCacheSeekBarListener.onCacheSeekBarStopChanged(playProgress);
                isSeeking = false;
            }
            return true;
        }
    }

    public interface OnCacheSeekBarListener {
        void onCacheSeekBarChanged(int progress);
        void onCacheSeekBarStopChanged(int progress);

    }
}
